package com.jnxx.task.controller;

import com.jnxx.task.domain.Shop;
import com.jnxx.task.domain.ShopReport;
import com.jnxx.task.dto.ReportDto;
import com.jnxx.task.dto.ReportFormDto;
import com.jnxx.task.service.IShopReportService;
import com.jnxx.task.service.IShopService;
import com.jnxx.task.vo.ReportVo;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.poi.ExcelUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.time.LocalDate;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * shopReportController
 * 
 * @author sh
 * @date 2024-01-08
 */
@RestController
@RequestMapping("/api/shopReport")
public class ShopReportController extends BaseController
{
    @Autowired
    private IShopReportService shopReportService;

    @Autowired
    private IShopService shopService;

    @Autowired
    private WechatController wechatController;

    /**
     * 查询shopReport列表
     */
//    @PreAuthorize("@ss.hasPermi('api:shopReport:list')")
    @GetMapping("/list")
    public TableDataInfo list(ShopReport shopReport)
    {
        startPage();
        List<ShopReport> list = shopReportService.selectShopReportList(shopReport);
        return getDataTable(list);
    }

    /**
     * 导出shopReport列表
     */
//    @PreAuthorize("@ss.hasPermi('api:shopReport:export')")
//    @Log(title = "shopReport", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, ShopReport shopReport)
    {
        List<ShopReport> list = shopReportService.selectShopReportList(shopReport);
        ExcelUtil<ShopReport> util = new ExcelUtil<ShopReport>(ShopReport.class);
        util.exportExcel(response, list, "shopReport数据");
    }

    /**
     * 获取shopReport详细信息
     */
//    @PreAuthorize("@ss.hasPermi('api:shopReport:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(shopReportService.selectShopReportById(id));
    }

    /**
     * 新增shopReport
     */
//    @PreAuthorize("@ss.hasPermi('api:shopReport:add')")
//    @Log(title = "shopReport", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ShopReport shopReport)
    {
        shopReport.setCreatTime(new Date());
        return toAjax(shopReportService.insertShopReport(shopReport));
    }

    /**
     * 修改shopReport
     */
//    @PreAuthorize("@ss.hasPermi('api:shopReport:edit')")
//    @Log(title = "shopReport", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody Map<String , ShopReport> map)
    {
        ShopReport report = map.get("report");
        System.out.println(report);
        return toAjax(shopReportService.updateShopReport(report));
    }

    /**
     * 删除shopReport
     */
//    @PreAuthorize("@ss.hasPermi('api:shopReport:remove')")
//    @Log(title = "shopReport", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(shopReportService.deleteShopReportByIds(ids));
    }

    /**
     * 根据负责人id和时间获取汇报任务
     * @param reportVo
     * @return
     */
    @PostMapping("/getByStaffIdAndTime")
    public AjaxResult getByStaffIdAndTime(@RequestBody ReportVo reportVo){
        List<ShopReport> shopReports = shopReportService.getByStaffIdAndTime(reportVo);
        return success(shopReports);
    }

    /**
     * 查询统计数据接口
     * @param reportVo
     * @return
     */
    @PostMapping("/getAllReportForStatistics")
    public AjaxResult getAllReportForStatistics(@RequestBody ReportVo reportVo){
        ReportDto reportDto = shopReportService.getAllReportForStatistics(reportVo);
        return success(reportDto);
    }

    /**
     * 获取所有时间段内未延迟完成的汇报
     * @param reportVo
     * @return
     */
    @PostMapping("/getReportDelay")
    public AjaxResult getReportDelay(@RequestBody ReportVo reportVo){
        List<ShopReport> shopReportList = shopReportService.getReportDelay(reportVo);
        return success(shopReportList);
    }

    /**
     * 查询表格数据
     * @param reportVo
     * @return
     */
    @PostMapping("/getReportform")
    public AjaxResult getReportform(@RequestBody ReportVo reportVo){
        List<ReportFormDto> formDtos = shopReportService.getReportform(reportVo);
        return success(formDtos);
    }

    /**
     * 创建每日汇报任务
     */
    @Scheduled(cron = "0 50 8 * * ?")
    public void createReportingTasks(){
        List<Shop> shops = shopService.selectAllShop();
        for (Shop shop : shops) {
            ShopReport shopReport = new ShopReport();
            shopReport.setStatus("0");
            shopReport.setShopId(shop.getId());
            shopReport.setStaffId(shop.getHead());
            shopReport.setCreatTime(new Date());
            LocalDate currentDate = LocalDate.now();
            LocalDate previousDay = currentDate.minusDays(1);
            shopReport.setTaskTime(previousDay);
            shopReportService.insertShopReport(shopReport);
        }
    }

    /**
     * 提醒完成每日汇报
     */
    @Scheduled(cron = "0 0 9 * * ?")
//    @GetMapping("/reminderReport")
    public void reminderReportAtNineThirty(){
        // 查询所有未完成汇报
        List<ShopReport> shopReportList = shopReportService.selectShopListByStatus("0");
        Map<String, List<ShopReport>> groupedByHeadName = shopReportList.stream()
                .collect(Collectors.groupingBy(ShopReport::getHeadName));
        groupedByHeadName.forEach((headName, reports) -> {
            HashMap<String,String> map = new HashMap<>();
            map.put("touser", headName);
            map.put("descript", "<div class=\"gray\">%s</div> <div class=\"normal\">您还有" + reports.size()+ "条每日汇报任务未提交，请在11点之前完成</div><div class=\"highlight\"></div>");
            wechatController.sendMessage(map);
        });
    }

        @Scheduled(cron = "0 0 10 * * ?")
//    @GetMapping("/reminderReport")
    public void reminderReportAtEleven(){
        // 查询所有未完成汇报
        List<ShopReport> shopReportList = shopReportService.selectShopListByStatus("0");
        Map<String, List<ShopReport>> groupedByHeadName = shopReportList.stream()
                .collect(Collectors.groupingBy(ShopReport::getHeadName));
        groupedByHeadName.forEach((headName, reports) -> {
            HashMap<String,String> map = new HashMap<>();
            map.put("touser", headName);
            map.put("descript", "<div class=\"gray\">%s</div> <div class=\"highlight\">您还有" + reports.size()+ "条每日汇报任务未提交，请在11点之前完成</div><div class=\"highlight\"></div>");
            wechatController.sendMessage(map);
        });
    }

}
